package com.cino.org.service.impl;
import com.cino.basic.base.mapper.BaseMapper;
import com.cino.basic.base.service.impl.BaseServiceImpl;
import com.cino.basic.util.PageList;
import com.cino.org.domain.Department;
import com.cino.org.mapper.DepartmentMapper;
import com.cino.org.query.DepartmentQuery;
import com.cino.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private BaseMapper<Department> baseMapper;

    @Override
    public List<Department> deptTree() {
        //获取所有的department对象
        HashMap<Long, Department> hashMap = new HashMap<>();
        List<Department> departments = baseMapper.loadAll();
        for (Department department : departments) {
            hashMap.put(department.getId(), department);
        }
        //前端需要得到的集合数据 - 部门树
        List<Department> deptTree = new ArrayList<>();

        for (Department department : departments) {
            if (department.getParent_id() == null) {
                deptTree.add(department);
            } else {//不是顶级部门
                //1.想办法找到当前部门的 父部门
                Long parent_id = department.getParent_id();
                //这种从数据库查询的方式，每次通过id去查询 -
                // 查询出来映射给实体domain，children集合中都会是空集合 - 没有任何数据
                Department parentDepartment = hashMap.get(parent_id);
                parentDepartment.getChildren().add(department);
                //常见问题：报空指针异常，原因：上级部门被删除
            }
        }
        return deptTree;
    }


}